# Create your views here.
import logging

import requests
from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from django.contrib.auth import login

from django.urls import reverse
from django.views import View
from django.shortcuts import render, redirect


from meiduo_mall.utils.response_code import RETCODE
from users.models import User
from .models import OAuthQQUser
from .utils import generate_access_token,check_access_token


logger=logging.getLogger('django')# 创建日志输出器
#提供qq登录扫码页面
class QQAuthURLView(View):
    def get(self,request):
        # 接收next
        next = request.GET.get('next')
        # 创建工具对象
        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                      client_secret=settings.QQ_CLIENT_SECRET,
                      redirect_uri=settings.QQ_CLIENT_URL,
                      state=next)
        # 生成qq登录扫码链接地址
        login_url=oauth.get_qq_url()

        # 返回
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'ok','login_url':login_url})

#处理QQ登录回调
class QQAuthUserView(View):
    def get(self,request):
        # 从参数中获取code
        code=request.GET.get('code')
        if code is None:
            return http.HttpResponseForbidden('获取code失败')

        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                      client_secret=settings.QQ_CLIENT_SECRET,
                      redirect_uri=settings.QQ_CLIENT_URL)
        try:
            # 根据code获取access_token
            access_token=oauth.get_access_token(code)
            # 根据access_token获取openid
            openid=oauth.get_open_id(access_token)
        except Exception as e:
            # 捕获异常
            logger.error(e)
            return http.HttpResponseServerError('oauth2.0认证失败')

        #根据openid判断该QQ用户是否绑定过美多商城的用户
        try:
            oauth_user=OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            # openid未绑定美多商城用户
                # 加密
            access_token_openid=generate_access_token(openid)
            context={'access_token_openid':access_token_openid}
            return render(request,'oauth_callback.html',context)
        else:
            # openid已经绑定美多商城用户
            # oauth_user.user表示从qq登录模型类中找到对应的用户模型类对象
            login(request,oauth_user.user)
            # 响应qq登录响应结果,重定向到state
            next = request.GET.get('state')
            response = redirect(reverse(next))
            # 将用户名写到cookie
            response.set_cookie('username', oauth_user.user.username, max_age=3600 * 24 * 14)
            return response

    def post(self,request):
    # 实现绑定用户的逻辑
        #  1、接受参数
        mobile=request.POST.get('mobile')
        password=request.POST.get('password')
        sms_code_client=request.POST.get('sms_code_client')
        access_token_openid=request.POST.get('access_token_openid')

        # 2、校验参数
        '''
        手机号，密码等校验
        '''
        # 判断openid是否有效，通过解密看是否有数据
        pass
        openid=check_access_token(access_token_openid)
        if openid is None:
            return render(request,'oauth_callback.html',{'openid_errmsg':'openid已经失效'})

        # 3、主体逻辑
        #3.1 使用手机号查询对应的用户是否存在
        try:
            user=User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user=User.objects.create_user(username=mobile,password=password,mobile=mobile)
        else:
            # 如果用户存在，需要校验密码
            if not user.check_password(password):
                return render(request,'oauth_callback.html',{'account_errmsg':'账号或者密码错误'})
        #3.2 将用户与openid绑定在一起
        # oauthqq_user=OAuthQQUser(user=user,openid=openid)
        # oauthqq_user.save()
        try:
            oauthqq_user=OAuthQQUser.objects.create(user=user,openid=openid)
        except Exception as e:
            logger.error(e)
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': '账号或者密码错误'})
        # 3.2 状态保持
        login(request,oauthqq_user.user)
        # 3.3 响应qq登录响应结果,重定向到state
        next = request.GET.get('state')
        response = redirect(reverse(next))
        #3.4  将用户名写到cookie
        response.set_cookie('username', oauthqq_user.username, max_age=3600 * 24 * 14)
        # 3.5  返回数据
        return response